<?php
namespace app\controller\clean;

use app\BaseController;
use Smalot\PdfParser\Parser;
use think\facade\Db;
use app\logic\RedisLogic;
use app\logic\ProjectLogic;
use app\model\HandleProject;
use app\model\HandleProjectRow;
use app\model\HandleProjectCases;
use app\model\HandleFileRow;
use app\model\HandleProjectTask;
use app\logic\FileLogic;
use think\Exception;
use think\exception\Handle;

class Stream extends BaseController
{
    // protected $rename_callback = 'test_rename_callback';
    // protected $check_file_callback = 'test_check_callback';
    // protected $mosaic_callback = 'test_mosaic_callback';
    protected $rename_callback = 'rename_callback';
    protected $check_file_callback = 'check_callback';
    protected $mosaic_callback = 'mosaic_callback';

    public function startTask()
    {
        $action_type = $this->request->param('action_type','');
        if($action_type==1){
            return $this->addChangeFileStream(); // 开启第一步改名
        }elseif($action_type == 3){
            return $this->addCompanyFileStream(); // 放入甲方资质文件
        }elseif($action_type == 4){
            return $this->addSupplyFilePutStream(); // 放入债转通知文件
        }elseif($action_type == 5){
            return $this->addMosaicFileAndContractStream(); // 打码债权清单文件，并放入
        }elseif($action_type == 6){
            return $this->addLawFirmFilePutStream(); // 放入律所生成相关文件
        }else{
            return json(errorMsg('错误的请求'));
        }
    }

    /**
     * 获取文件改名对照结构化数据
     * @return array
     */
    private function renameFileData()
    {
        $fileData = Db::name('handle_file_name')->column('new_name','old_name');
        return $fileData;
    }

    /**
     * 添项目清洗任务 stream
     */ 
    public function addChangeFileStream()
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        if($this->request->fhUuid == ''){
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        $contracts = array_keys($caseDetailData);
        $bash_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR."1、基础清洗文件";

        // 如果不是第一次清洗那么只清洗，缺失文件的甲标案件
        if($projectInfo['clean_status'] !== 0){
            $contracts = HandleFileRow::ins()->where([['project_uuid','=',$this->request->fhUuid],['state','=',3],['clean_type','=',1]])->column('case_dir');
            HandleFileRow::ins()->where([['project_uuid', '=', $this->request->fhUuid],['clean_type','=',1]])->delete(); 
        }

        $contrast_table = $this->renameFileData();
        foreach($contracts as $jb){
            $type = 'file_change_name_by_table';
            $stream_data['dir_path'] = $bash_path.DIRECTORY_SEPARATOR.$jb;
            $stream_data['contrast_table'] = $contrast_table;
            $stream_result = RedisLogic::ins()->addTaskStream($type,$stream_data,$this->rename_callback);
            $insert_data['task_id'] = $stream_result['data'][1];
            $insert_data['project_uuid'] = $this->request->fhUuid;
            $insert_data['case_dir'] = $jb;
            $insert_data['state'] = 0;
            // 写入数据库
            $r = HandleProjectRow::ins()->insert($insert_data);
        }
        HandleProject::ins()->where(['uuid' => $this->request->fhUuid])->update(['clean_status'=>1]); // 清洗状态
        HandleProjectTask::ins()->whereIn('task_name',['文件检索','普通类文件'])->where('project_uuid',$this->request->fhUuid)->update(['state'=>1]);

        return json(successMsg('数据清洗中...')); 
    }

    /**
     * 读取改名后回调队列查看改名结果和进度  [用] “文件检索结果触发”
     */
    public function readRenameCallback($projectInfo) 
    {
        // $this->request->fhUuid = $this->request->param('_uuid_','');
        // $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        
        $error_num = 0;
        $success_num = 0;
        $task_msg = RedisLogic::ins()->callbackStream($this->rename_callback);
        if(!empty($task_msg)){
            foreach($task_msg as $msg){
                if($msg['result']['status'] == 'error'){
                    $up_data['state'] = 3;
                    $up_data['result_msg'] = $msg['result']['message'];
                    HandleProjectRow::ins()->where('task_id',$msg['task_id'])->update($up_data);
                    $error_num++;
                }else{
                    $up_data['state'] = 1;
                    $up_data['result_msg'] = $msg['result']['message'];
                    HandleProjectRow::ins()->where('task_id',$msg['task_id'])->update($up_data);
                    $success_num++;
                }
            }
        }
        // 单任务 
        if($error_num !== 0 || $success_num !== 0){
            $projectInfo['clean_success_total'] = $projectInfo['clean_success_total']+$success_num;
            if($projectInfo['clean_status'] ==1){
                $projectInfo['clean_exception_total'] = $projectInfo['clean_exception_total'] + $error_num;
            }else{
                $projectInfo['clean_exception_total'] = $error_num;
            }
            
            unset($projectInfo['create_data']);
            HandleProject::ins()->where(['uuid' => $this->request->fhUuid])->update($projectInfo); // 更新案件清洗数量
        }
        
        $lv = round($projectInfo['clean_success_total']/$projectInfo['case_total'],2)*100;
        $zxlv = round(($projectInfo['clean_success_total']+$projectInfo['clean_exception_total'])/$projectInfo['case_total'],2)*100;

        if($lv>=100){
            HandleProject::ins()->where(['uuid' => $this->request->fhUuid])->update(['clean_status'=>3]); // 清洗完成状态 3
            HandleProjectTask::ins()->whereIn('task_name',['文件检索','普通类文件'])->update(['state'=>3]);
            // 清洗完成后自动开启文件缺失检查
            $this->checkFileStatusStream(1,$this->request->fhUuid);
        }elseif($zxlv>=100){
            HandleProject::ins()->where(['uuid' => $this->request->fhUuid])->update(['clean_status'=>2]); // 清洗待完成,点击进入二次，或最终清洗 2
        }else{
            $msg = '清洗案件个数： '.$projectInfo['case_total']." 个,成功案件个数： ".$projectInfo['clean_success_total']." 个,失败案件个数： ".$projectInfo['clean_exception_total']." 个，执行率： ".$zxlv."，完成率： ".$lv.'。 请继续等待完成！';
            return json(errorMsg($msg));
        }
        
    }

    /**
     * 清洗后返回的异常文件名列表 // 点击 “文件检索结果触发”
     */
    public function exceptionFileName()
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $clean_result = $this->readRenameCallback($projectInfo);  // 读取改名后回调队列查看改名结果和进度
        if($clean_result){
            return json($clean_result);
        }
        $exception_row = HandleProjectRow::ins()->where('project_uuid',$this->request->fhUuid)->where('state',3)->column('result_msg');
        if(empty($exception_row)){
            return json(successMsg('未发现有异常文件名'));
        }
        $error_file_list =[];
        foreach($exception_row as $row){
            $file = str_replace('未找到文件名映射: ','',$row);
            if(mb_strpos($file,', ') === false){
                $old_file_name  = pathinfo($file)['filename'];
                $error_file_list[] = $old_file_name;
            }else{
                $files = explode(', ',$file);
                foreach($files as $old_file){
                    $old_file_name  = pathinfo(trim($old_file))['filename'];
                    $error_file_list[] = $old_file_name;
                }
            }
        }
        $error_file_list = array_unique($error_file_list);
        return json(successMsg('请求成功',$error_file_list));
    }

    /**
     * 添加文件改名结构化数据
     */
    public function addFileNameData()
    {
    
        $rename_list = $this->request->param('data');
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $insert_data = [];
        foreach($rename_list as $k => $v){
            if(trim($v['name']) == '' || trim($v['value']) == ''){
                return json(errorMsg('提交数据不全，请继续补充'));
            }
            $insert_data[$k]['old_name'] = $v['name'];
            $insert_data[$k]['new_name'] = $v['value'];
        }
        $result = Db::name('handle_file_name')->insertAll($insert_data);
        if($result){
            $cleanResult = ProjectLogic::ins()->againChangeFileStream($this->request->fhUuid,$projectInfo);
            return json($cleanResult);
        }else{
            return json(errorMsg('添加异常，重试'));
        }
    }

    /**
     * 添加检查文件缺失任务队列 
     */
    public function checkFileStatusStream($check_type,$uuid)
    {
        // $this->request->fhUuid = $this->request->param('_uuid_','');
        $this->request->fhUuid = $uuid;
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        $bash_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR."1、基础清洗文件";
        $type = 'file_name_check';
        foreach($caseDetailData as $case => $info){
            if($check_type === 1){ // 类型一：检查基础文件是否缺失
                if((bool)$info[2] ==true && (bool)$info[3] ==false){
                    // 1. 有代偿无回购
                    $stream_data['file_list'] = $this->checkFileTypeList()[0][0];
                }elseif((bool)$info[2] ==false && (bool)$info[3] ==true){
                    // 2.无代偿有回购
                    $stream_data['file_list'] = $this->checkFileTypeList()[0][1];
                }elseif((bool)$info[2] ==true && (bool)$info[3] ==true){
                    // 3. 有代偿有回购无反担保
                    $stream_data['file_list'] = $this->checkFileTypeList()[0][2];
                }
            }elseif($check_type === 2){ // 检查 甲方资质类文件
                $stream_data['file_list'] = $this->checkFileTypeList()[1][0];
                
            }elseif($check_type === 3){ // 检查 债权通知类文件
                if((bool)$info[6] == true){
                    // 1. 有反担保
                    $stream_data['file_list'] = $this->checkFileTypeList()[2][0];
                    foreach($stream_data['file_list'] as $k=>$v){
                        $stream_data['file_list'][$k] = str_replace('反担保',$info[6],$v);
                    }
                }else{
                    // 2. 担保
                    $stream_data['file_list'] = $this->checkFileTypeList()[2][1];
                }
            }elseif($check_type === 4){ // 检查 债权协议及清单文件
                if((bool)$info[6] == true){
                    // 1. 有反担保
                    $stream_data['file_list'] = $this->checkFileTypeList()[3][0];
                    foreach($stream_data['file_list'] as $k=>$v){
                        $stream_data['file_list'][$k] = str_replace('反担保',$info[6],$v);
                    }
                }else{
                    // 2. 担保
                    $stream_data['file_list'] = $this->checkFileTypeList()[3][1];
                }
            }else{ // 异常检查
                return json(errorMsg('检查异常'));
            }
            
            $stream_data['dir_path'] = $bash_path.DIRECTORY_SEPARATOR.$case;
            $stream_result = RedisLogic::ins()->addTaskStream($type,$stream_data,$this->check_file_callback);
            $insert_data['task_id'] = $stream_result['data'][1];
            $insert_data['project_uuid'] = $this->request->fhUuid;
            $insert_data['case_dir'] = $case;
            $insert_data['clean_type'] = $check_type;
            $insert_data['state'] = 0;
            $r = HandleFileRow::ins()->insert($insert_data);
        }
        // return json(successMsg('文件检查中...')); 
    }

    /**
     * 读取文件缺失检查的回调队列，记录缺失文件，和检查进度
     */
    public function readCheckFileCallback($action=true)
    {
        // $this->request->fhUuid = $this->request->param('_uuid_','');
        // $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        // if(empty($projectInfo))
        // {
        //     return json(errorMsg('请求参数_uuid_有误'));
        // }
        
        $error_num = 0;
        $success_num = 0;
        $task_msg = RedisLogic::ins()->callbackStream($this->check_file_callback);
        if(!empty($task_msg)){
            foreach($task_msg as $msg){
                if($msg['result']['status'] == 'success'){
                    if(empty($msg['result']['missing_files'])){
                        $up_data['state'] = 1;
                        $up_data['file_list'] = '';
                        $success_num++;
                    }else{
                        $up_data['state'] = 3;
                        $up_data['file_list'] = join(',',$msg['result']['missing_files']);
                        $error_num++;
                    }
                    HandleFileRow::ins()->where('task_id',$msg['task_id'])->update($up_data);
                    
                }else{  // 异常值
                    $error_num++;
                }
            }
        }

        // $msg = '清洗案件个数： '.$projectInfo['case_total']." 个,正常案件个数： ".$success_num." 个,缺文件案件个数： ".$error_num." 个";
        // return json(successMsg($msg));
        if($action !== true){
            // echo '定时任务执行中...';
        }
    }

    /**
     * 下载清洗
     * @return \think\response\Json
     */
    public function downloadCheckFileExcel()
    {
        $fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }

        // 优先读取文件检查回调队列拉去检查数据
        $this->readCheckFileCallback(); 

        // 查询检查表里有没有没完成的任务
        $incomplete_number = HandleFileRow::ins()->where('project_uuid',$fhUuid)->where('state',0)->count();
        if($incomplete_number > 0 ){
            return json(errorMsg('任务还在执行中，稍后再下载缺失文件...'));
        }

        // 更新当前执行状态为1的都执行成功为3
        HandleProjectTask::ins()->where('state',1)->update(['state'=>3]);
        // 查询当前项目 案件缺失文件记录
        $exception_row = HandleFileRow::ins()->field('case_dir,file_list')->where([['project_uuid', '=', $fhUuid],['state', '=', 3]])->select()->toArray();
        $excelData = [];
        foreach($exception_row as $row){
            if(isset($excelData[$row['case_dir']])){
                $excelData[$row['case_dir']] .= ','.$row['file_list'];
            }else{
                $excelData[$row['case_dir']] = $row['file_list'];
            }
        }
        
        $zj_type_list = ["1. 有代偿无回购有反担保","2. 有代偿无回购无反担保","3. 无代偿有回购有反担保","4. 无代偿有回购无反担保","5. 有代偿有回购有反担保","6. 有代偿有回购无反担保"];
        $data = [['甲方标识','缺失文件','证据目录类型']];
        $caseDetail = HandleProjectCases::where('project_uuid', $fhUuid)->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        foreach($caseDetailData as $case => $info){
            if((bool)$info[2] ==true && (bool)$info[3] ==false && (bool)$info[6] == true){
                // 1. 有代偿无回购有反担保
                $zj_type = $zj_type_list[0];
            }elseif((bool)$info[2] ==true && (bool)$info[3] ==false && (bool)$info[6] == false){
                // 2. 有代偿无回购无反担保
                $zj_type = $zj_type_list[1];
            }elseif((bool)$info[2] ==false && (bool)$info[3] ==true && (bool)$info[6] == true){
                // 3.无代偿有回购有反担保
                $zj_type = $zj_type_list[2];
            }elseif((bool)$info[2] ==false && (bool)$info[3] ==true && (bool)$info[6] == false){
                // 4.无代偿有回购无反担保
                $zj_type = $zj_type_list[3];
            }elseif((bool)$info[2] ==true && (bool)$info[3] ==true && (bool)$info[6] == true){
                // 5. 有代偿有回购有反担保
                $zj_type = $zj_type_list[4];
            }elseif((bool)$info[2] ==true && (bool)$info[3] ==true && (bool)$info[6] == false){
                // 5. 有代偿有回购无反担保
                $zj_type = $zj_type_list[5];
            }else{
                $zj_type = '异常类型请核对！';
            }
            if(isset($excelData[$case])){
                $filelist = $excelData[$case];
            }else{
                $filelist = '';
            }
            $data[] = [$case,$filelist,$zj_type];

        }
        FileLogic::ins()->downExeclFile($data, '洋钱罐案件文件缺失记录-' . date('YmdHis'));
        exit();
    }

    /**
     * 文件检查文件名结构化数据
     * @return array[]
     */
    public function checkFileTypeList()
    {
        $data_type_list = [
            [
                [
                    "借款合同", "被告人脸识别照片", "放款凭证", "委托担保合同", "还款情况表", "被告身份证照片正面", "被告身份证照片反面", "代偿证明"
                ],
                [
                    "借款合同", "被告人脸识别照片", "放款凭证", "委托担保合同", "还款情况表", "被告身份证照片正面", "被告身份证照片反面", "代偿证明（回购）"
                ],
                [
                    "借款合同", "被告人脸识别照片", "放款凭证", "委托担保合同", "还款情况表", "被告身份证照片正面", "被告身份证照片反面", "代偿证明（回购）", "代偿证明"
                ]
            ],
            [
                [
                    "金融许可证和营业执照", "融资担保业务经营许可证和营业执照"
                ]
            ],
            [
                [
                    "债权转让通知（担保-反担保）", "债权转让通知（反担保-原告）",
                ],
                [ 
                    "债权转让通知（担保-原告）" 
                ]
            ],
            [
                [
                    "债权转让协议及清单（担保-反担保）", "债权转让协议及清单（反担保-原告）",
                ],
                [ 
                    "债权转让协议及清单（担保-原告）" 
                ]
            ]

        ];
        return $data_type_list;
    }
    
    /**
     * 放入甲方资质文件 2
     */
     public function addCompanyFileStream()
     {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        // 如果不是第一次清洗那么只清洗，缺失文件的甲标案件
        $cleanState = HandleProjectTask::ins()->where([['task_name','=','资质类文件'],['project_uuid','=',$this->request->fhUuid]])->value('state');
        $contracts = [];
        if($cleanState !== 0){
            $contracts = HandleFileRow::ins()->where([['project_uuid','=',$this->request->fhUuid],['state','=',3],['clean_type','=',2]])->column('case_dir');
            $contracts = array_unique($contracts);
            if(empty($contracts)){
                json(errorMsg('不缺数据文件，无需二次清洗'));
            }
        }
        
        HandleFileRow::ins()->where([['project_uuid', '=', $this->request->fhUuid],['clean_type','=',2]])->delete(); 
        $project_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR;
        $bash_case_path = $project_path."1、基础清洗文件";
        $company_file_path = $project_path;
        $stream_result = [];
        foreach($caseDetailData as $case => $info ){
            if(!empty($cleanState)){
                if (!in_array($case, $contracts)) {
                    continue;
                }else{
                }
            }
            $type = 'file_transfer';
            if($info[4] !== NULL && trim($info[4]) !== ''){ // 放入 金融许可证和营业执照 
                $stream_data['file_path'] = $company_file_path.'2、资质文件'.DIRECTORY_SEPARATOR.'01金融许可证和营业执照-'.$info[4].'.pdf';
                $stream_data['base_path'] = $bash_case_path;
                $stream_data['new_file_name'] = '金融许可证和营业执照.pdf';
                $stream_data['proof_list'] = [(string) $case];
                $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            }else{
                // $stream_result['error'][] = 'error';
            }
            $stream_data['file_path'] = $company_file_path.'2、资质文件'.DIRECTORY_SEPARATOR.'02融资担保业务经营许可证和营业执照-黑龙江三农信融资担保有限公司.pdf';
            $stream_data['base_path'] = $bash_case_path;
            $stream_data['new_file_name'] = '融资担保业务经营许可证和营业执照.pdf';
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
        }
        if($stream_result){
            // 放入任务完成后开启对应文件文件缺失检查任务
            $this->checkFileStatusStream(2,$this->request->fhUuid);
            HandleProjectTask::ins()->where([['task_name','=','资质类文件'],['project_uuid','=',$this->request->fhUuid]])->update(['state'=>1]);
            // 检查文件缺失 只检查通知类文件
            return json(successMsg('甲方资质文件放入中...'));
        }
     }

    /**
     * 放入债权转让通知文件 3
     */
    public function addSupplyFilePutStream()
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }

        // 如果不是第一次清洗那么只清洗，缺失文件的甲标案件
        $cleanState = HandleProjectTask::ins()->where([['task_name','=','通知类文件'],['project_uuid','=',$this->request->fhUuid]])->value('state');
        $contracts = [];
        if($cleanState !== 0){
            $contracts = HandleFileRow::ins()->where([['project_uuid','=',$this->request->fhUuid],['state','=',3],['clean_type','=',3]])->column('case_dir');
            $contracts = array_unique($contracts);
            if(empty($contracts)){
                json(errorMsg('不缺数据文件，无需二次清洗'));
            }
        }
        HandleFileRow::ins()->where([['project_uuid', '=', $this->request->fhUuid],['clean_type','=',3]])->delete(); 
        $project_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR;
        $bash_case_path = $project_path."1、基础清洗文件";
        $supply_file_path = $project_path;
        $stream_result = [];
        foreach($caseDetailData as $case => $info ){
            // 如果缺失文件
            if(!empty($cleanState)){
                if (!in_array($case, $contracts)) {
                    continue;
                }
            }
            $type = 'file_transfer';
            if($info[6] !== NULL && trim($info[6]) !== ''){ // 担保到反担保 ， 反担保到原告
                $stream_data['file_path'] = $supply_file_path.DIRECTORY_SEPARATOR.'3、担保-反担保-通知'.DIRECTORY_SEPARATOR.$case.DIRECTORY_SEPARATOR.'债转短信通知记录.pdf';
                $stream_data['base_path'] = $bash_case_path;
                $stream_data['new_file_name'] = '债权转让通知（担保-'.trim($info[6]).'）.pdf';
                $stream_data['proof_list'] = [(string) $case];
                $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);

                $stream_data['file_path'] = $supply_file_path.DIRECTORY_SEPARATOR.'4、反担保-原告-通知'.DIRECTORY_SEPARATOR.$case.DIRECTORY_SEPARATOR.'债转短信通知记录.pdf';
                $stream_data['base_path'] = $bash_case_path;
                $stream_data['new_file_name'] = '债权转让通知（'.trim($info[6]).'-原告）.pdf';
                $stream_data['proof_list'] = [(string) $case];
                $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            // }elseif(empty(trim($info[6])) && trim($info[5]) == '三农信' ){ // 担保到原告
            }elseif(($info[6] === NULL ||empty(trim($info[6]))) && trim($info[5]) !=='' ){ // 担保到原告
                $stream_data['file_path'] = $supply_file_path.DIRECTORY_SEPARATOR.'5、担保-原告-通知'.DIRECTORY_SEPARATOR.$case.DIRECTORY_SEPARATOR.'债转短信通知记录.pdf';
                $stream_data['base_path'] = $bash_case_path;
                $stream_data['new_file_name'] = '债权转让通知（担保-原告）.pdf';
                $stream_data['proof_list'] = [(string) $case];
                $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            }else{
                // $stream_result['error'][] = 'error';
            }
        }

        if($stream_result){
            // 放入任务完成后开启对应文件文件缺失检查任务 3
            $this->checkFileStatusStream(3,$this->request->fhUuid);
            HandleProjectTask::ins()->where([['task_name','=','通知类文件'],['project_uuid','=',$this->request->fhUuid]])->update(['state'=>1]);
            // 检查文件缺失 只检查通知类文件
            return json(successMsg('债权转让通知放入中...'));

        }
    }

    /**
     * 债转协议放入+清单打码放入 4
     */
    public function addMosaicFileAndContractStream()
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        // 读取 债转协议清单任务状态，如果不是未执行，那么禁止清洗。
        $mocaicState = HandleProjectTask::ins()->where([['task_name','=','债转协议清单'],['project_uuid','=',$this->request->fhUuid]])->value('state');

        if($mocaicState>0){
            return json(errorMsg('债转协议及清单，禁止二次清洗！！！'));
        }
        // $project_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR;
        $project_path = FileLogic::ins()->getLocalCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR;

        $pdf_dir = $project_path."6、债转协议及清单/2、协议清单文件PDF文本/";
        $base_dir = $project_path."1、基础清洗文件/";

        $parser = new Parser();
        $pdf_list = scandir($pdf_dir);
        foreach ($pdf_list as $file){
            $ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
            $file_name = pathinfo($file,PATHINFO_FILENAME);
            if($ext !== 'pdf') continue;

            $pdf = $parser ->parseFile($pdf_dir.$file);
            $pages = $pdf->getPages();  // 按页做维度读取内容对象

            foreach ($pages as $index => $page) {
                $p = $page->getPageNumber();
                $text = trim($page->getText());
                preg_match_all('#\b\d+\s+(\d+)\s+(\S+)\s+\d{6}#',$text,$matches);
                foreach ($matches[1] as $k=>$v){
                    $mosiac_file_type = 'YQG_pdf_mosaic';
                    $mosaic_file_path = $project_path."6、债转协议及清单/".$file_name.'扫描件'.DIRECTORY_SEPARATOR.$file_name.'扫描件_'.($p+1).'.pdf';
                    $case_path = $base_dir.$v;
                    $case_file_name = $file_name.'.pdf';
                    $mosaic_data['file_path'] = $mosaic_file_path;
                    $mosaic_data['new_file_dir'] = $case_path;
                    $mosaic_data['new_file_name'] = $case_file_name;
                    $mosaic_data['keywords'] = [(string) $v];
                    $stream_result[] = RedisLogic::ins()->addTaskStream($mosiac_file_type,$mosaic_data,$this->mosaic_callback);
                    $add_file_type = 'file_transfer';
                    $xy_file = str_replace('_1','',$file_name).'.pdf';
                    $stream_data['file_path'] = $project_path."6、债转协议及清单/1、全部协议文件".DIRECTORY_SEPARATOR.$xy_file;
                    $stream_data['base_path'] = $case_path;
                    $stream_data['new_file_name'] = $xy_file;
                    $stream_data['proof_list'] = [(string) $v];
                    $stream_result[] = RedisLogic::ins()->addTaskStream($add_file_type,$stream_data);
                }
            }
        }
        if($stream_result){
            // 放入任务完成后开启对应文件文件缺失检查任务 4
            $this->checkFileStatusStream(4,$this->request->fhUuid);
            HandleProjectTask::ins()->where([['task_name','=','债转协议清单'],['project_uuid','=',$this->request->fhUuid]])->update(['state'=>1]);
            // 检查文件缺失 只检查通知类文件
            return json(successMsg('债权转让协议打码并放入中...'));
        }
    }

    /**
     * 原告资质类文件放入（补充类文件）
     */
    public function addLawFirmFilePutStream()
    {
        $this->request->fhUuid = $this->request->param('_uuid_','');
        $projectInfo = ProjectLogic::ins()->getProjectInfo($this->request->fhUuid);
        if(empty($projectInfo))
        {
            return json(errorMsg('请求参数_uuid_有误'));
        }
        $this->request->fhTitle = $projectInfo['title'];
        $this->request->fhDate = substr($projectInfo['create_time'],0,10);
        $caseDetail = HandleProjectCases::where(['project_uuid' => $this->request->fhUuid])->value('data_content');
        if($caseDetail == ''){
            return json(errorMsg('请先上传要素表'));
        }
        $caseDetailData = json_decode($caseDetail,true);
        if(json_last_error() !== JSON_ERROR_NONE)
        {
            return json(errorMsg('要素表数据异常，请重新上传'));
        }
        $project_path = FileLogic::ins()->getCleanFileDir(3).DIRECTORY_SEPARATOR.$this->request->fhDate.DIRECTORY_SEPARATOR.$this->request->fhTitle.DIRECTORY_SEPARATOR;

        $pdf_dir = $project_path."7、补充文件/";
        $base_dir = $project_path."1、基础清洗文件/";

        foreach($caseDetailData as $case=>$info){
            $type = 'file_transfer';
            $old_file_name = '律师事务所诉讼代理函-'.$info[1].'-'.$case.'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '授权委托书-'.$info[1].'-'.$case.'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '民事起诉状-'.$info[1].'-'.$case.'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '律师执业证--'.$info[7].'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '律师执业证--'.$info[8].'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '送达地址确认书--'.$info[7].'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
            $old_file_name = '网上开庭申请书--'.$info[7].'.pdf';
            $stream_data['file_path'] = $pdf_dir.$old_file_name;
            $stream_data['base_path'] = $base_dir;
            $stream_data['new_file_name'] = $old_file_name;
            $stream_data['proof_list'] = [(string) $case];
            $stream_result[] = RedisLogic::ins()->addTaskStream($type,$stream_data);
        }

        if($stream_result){
            HandleProjectTask::ins()->where([['task_name','=','补充类文件'],['project_uuid','=',$this->request->fhUuid]])->update(['state'=>1]);
            return json(successMsg('原告资质放入中...'));
        }
        
    }
}